<template>
  <fks-dialog
    :visible="true"
    :append-to-body="true"
    width="960px"
    destroy-on-close
    :title="title"
    @close="close"
  >
    <div slot="title">
      <i
        v-if="userType == 'add'"
        class="fks-icon-plus"
      />
      <i
        v-if="userType == 'edit'"
        class="fks-icon-edit"
      />
      <i
        v-if="userType == 'view'"
        class="fks-icon-view"
      />
      {{ title }}
    </div>
    <fks-form
      ref="Form"
      :model="Form"
      :rules="rules"
      :disabled="disabled"
      label-width="85px"
    >
      <!-- 姓名 -->
      <fks-form-item
        :span="12"
        lead
        :label="LANG.USER_FULL_NAME"
        prop="userFullname"
      >
        <fks-input
          v-model="Form.userFullname"
          :disabled="userType == 'view'"
          :placeholder="LANG.USER_USERFULLNAME_PLACEHOLDER"
          maxlength="50"
          show-word-limit
        />
      </fks-form-item>
      <!-- 性别 -->
      <fks-form-item
        :span="12"
        :label="LANG.SEX"
        prop="sex"
      >
        <fks-select
          v-model="Form.sex"
          style="width: 100%"
          :placeholder="LANG.PLEASE_SELECT"
        >
          <fks-option
            :label="LANG.MALE"
            :value="LANG.MALE"
          />
          <fks-option
            :label="LANG.FEMALE"
            :value="LANG.FEMALE"
          />
        </fks-select>
      </fks-form-item>
      <!-- 编辑时用户名不能修改 -->
      <fks-form-item
        :span="12"
        lead
        :label="LANG.USERNAME"
        prop="userName"
      >
        <fks-input
          v-model="Form.userName"
          :disabled="userType == 'edit'"
          :placeholder="LANG.USERMANAGEMENT_USERNAME_PLACEHOLDER"
          maxlength="50"
          show-word-limit
        />
      </fks-form-item>
      <fks-form-item
        :span="12"
        :label="LANG.EMAIL"
        prop="email"
      >
        <fks-input
          v-model="Form.email"
          :placeholder="LANG.USERMANAGEMENT_EMAIL_PLACEHOLDER"
          maxlength="50"
          show-word-limit
        />
      </fks-form-item>
      <fks-form-item
        :span="12"
        lead
        :label="LANG.PHONE"
        prop="phone"
      >
        <fks-input
          v-model="Form.phone"
          maxlength="11"
          show-word-limit
          :placeholder="LANG.USERMANAGEMENT_CONTACT_PLACEHOLDER"
        />
      </fks-form-item>
      <!-- 用户使用周期 -->
      <fks-form-item
        :span="12"
        :label="LANG.ACCOUNT_PERIOD"
        prop="accountPeriod"
      >
        <fks-select
          v-model="Form.accountPeriod"
          style="width: 100%"
        >
          <fks-option
            :label="LANG.LANG_TIME"
            :value="1"
          />
          <fks-option
            :label="LANG.SHORT_TIME"
            :value="2"
          />
        </fks-select>
      </fks-form-item>
      <!-- 新增用户时 为密码-->
      <fks-form-item
        v-if="userType == 'add'"
        :span="12"
        :label="LANG.PASSWORD"
        lead
        prop="password"
      >
        <fks-input
          v-model="Form.password"
          show-password
          maxlength="50"
          :placeholder="LANG.USERMANAGEMENT_PASSWORD_PLACEHOLDER"
        />
      </fks-form-item>
      <!-- 编辑用户时 为更改密码 -->
      <fks-form-item
        v-if="userType == 'edit'"
        :span="12"
        lead
        :label="LANG.EDIT_PASSWORD"
        prop="password"
      >
        <fks-input
          v-model="Form.password"
          show-password
          maxlength="50"
        />
      </fks-form-item>
      <!-- 密码设置提示 -->
      <fks-form-item>
        <fks-alert
          v-if="userType !== 'view'"
          style="height: auto"
          type="info"
          show-icon
          :closable="false"
        >
          <div slot="title">
            <span>{{ LANG.USER_PASSWORD_TIP }}</span>
            <span style="font-size: 14px">
              {{ LANG.PASSWORD_TIP }}{{ accountConfig.pwMinLength }}-{{
                accountConfig.pwMaxLength
              }}
            </span>
            <span
              v-if="
                accountConfig.charDemand == '1' &&
                  (accountConfig.passwordLevel == 'custom' ||
                  accountConfig.passwordLevel == 'normal')
              "
            >{{ LANG.PASSWORD_TIP1 }}</span>
            <span
              v-if="
                accountConfig.charDemand == '2' &&
                  accountConfig.passwordLevel == 'custom'
              "
            >{{ LANG.PASSWORD_TIP2 }}</span>
            <span
              v-if="
                accountConfig.charDemand == '3' &&
                  accountConfig.passwordLevel == 'custom'
              "
            >{{ LANG.PASSWORD_TIP3 }}</span>
            <span v-if="accountConfig.sensitiveInfo == true">{{
              LANG.SENSITIVE_INFO_TIP
            }}</span>
          </div>
        </fks-alert>
      </fks-form-item>
    </fks-form>
    <template slot="footer">
      <fks-button
        v-if="userType != 'view'"
        type="primary"
        :loading="userLoading"
        icon="fks-icon-check"
        @click="save"
      >
        <span style="margin-left: 4px">{{ LANG.SAVE }}</span>
      </fks-button>
    </template>
  </fks-dialog>
</template>
<script>
import * as System from "../api";
import { mapState } from "vuex";
import { pwdEncrypt } from "@/utils/encryption/pwd";
import * as stateTypes from "@/store/State/stateTypes";
import { pwdRuleCheck } from "@/utils/password";
export default {
	name: "UserInfo",
	components: {},
	props: {
		data: {
			default() {
				return {
					userName: "",
				};
			},
		},
		userType: {
			type: String,
			default: "add",
		},
		visible: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			userName: "",
			userLoading: false, //防抖
			copyPassword: "",
			//导入用户弹出 显隐
			//上传的地址
			rowData: {}, //编辑时，克隆原始数据
			diffData: {}, //差异数据，编辑修改保存时，只上传修改过的数据
			disabled: false,
			passwordWarning: false,
			Form: {
				name: "",
				sex: "",
				userName: "",
				password: "",
				email: "",
				phone: "",
				orgNo: "",
				orgName: "",
				//新增时 默认长期
				accountPeriod: 1,
			},
		};
	},
	computed: {
		title() {
			switch (this.userType) {
				case "add":
					return this.LANG.ADD;
				case "view":
					return this.LANG.VIEW;
				default:
					return this.LANG.EDIT;
			}
		},
		//验证规则
		rules() {
			return {
				userFullname: [
					{
						required: this.userType == "add" ? true : false,
						message: this.LANG.USERFULLNAME_NOT_EMPTY,
						trigger: "blur",
					},
				],
				password: [
					{
						//新增用户时，必须填密码，编辑时不一定要修改密码
						required: this.userType == "add" ? true : false,
						message: this.LANG.USERMANAGEMENT_PASSWORDRULE,
						trigger: "blur",
					},
				],
				userName: [
					{
						required: this.userType == "add" ? true : false,
						message: this.LANG.USERNAME_NOT_EMPTY,
						trigger: "blur",
					},

					{
						pattern: this.userType == "add" ? /^[a-z][a-z0-9_]*$/g : "",
						message: this.LANG.FORMAT_ERROR,
					},
				],
				sex: [
					{
						required: true,
						message: this.LANG.USER_SEX_REQUIRED,
						trigger: "change",
					},
				],
				email: [
					{
						required: true,
						message: this.LANG.EMAIL_NOT_EMPTY,
						trigger: "blur",
					},
					{
						pattern: /^[A-Za-z0-9_]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g,
						message: this.LANG.FORMAT_ERROR,
					},
				],
				phone: [
					{
						required: true,
						message: this.LANG.PHONE_NOT_EMPTY,
						trigger: "blur",
					},
					{
						pattern: /^1[3456789]\d{9}$/g,
						message: this.LANG.FORMAT_ERROR,
					},
				],
			};
		},
		type() {
			return this.$store.state.portal.type;
		},
		portalId() {
			return this.$store.state.portal.id;
		},
		...mapState([stateTypes.ACCOUNT_CONFIG]),
	},

	watch: {
		data: {
			deep: true,
			immediate: true,
			handler(val) {
				if (this.userType == "edit") {
					this.rowData = JSON.parse(JSON.stringify(val));
					this.Form = JSON.parse(JSON.stringify(val));
				}
				if (this.userType == "view") {
					this.Form = val;
					this.disabled = true;
				}
				if (this.userType == "add") {
					this.Form.password = this.accountConfig.initialPassword;
				}
			},
		},
		visible() {
			this.show = this.visible;
		},
	},

	methods: {
		close() {
			this.$refs.Form.clearValidate();
			this.$emit("update:visible", false);
		},
		diffDataMethod() {
			//保存时 比较修改的对象，筛选出修改的值，提交时只需要提交修改的值。
			for (let i in this.rowData) {
				if (i != "password") {
					if (this.rowData[i] != this.Form[i]) {
						if (!this.diffData) {
							this.diffData = {};
						}
						this.diffData[i] = this.Form[i];
					}
				}
				if (i == "password") {
					if (this.Form.password) {
						if (pwdRuleCheck(this.Form.password)) {
							this.diffData[i] = pwdEncrypt(this.Form[i]);
							this.passwordWarning = false;
						} else {
							this.$message.error(this.LANG.PASSWORD_VALID_TIP);
							this.passwordWarning = true;
						}
					}
				}
			}
		},
		save() {
			this.$refs.Form.validate((valid) => {
				if (valid) {
					this.userLoading = true;
					if (this.title == this.LANG.EDIT) {
						//找出修改数据
						this.passwordWarning = false;
						this.diffDataMethod();
						if (this.passwordWarning == false) {
							// 修改过，则调用接口，提交修改,参数要带上用户名&id
							System.editUsers(
								JSON.stringify(
									Object.assign(
										{ userName: this.Form.userName, id: this.Form.id },
										this.diffData
									)
								)
							)
								.then((response) => {
									this.userLoading = false;
									//清除上次修改对象
									this.diffData = {};
									if (response.status) {
										//修改成功后，清除上次修改对象
										this.close();
										this.$message.success(this.LANG.EDIT_SUCCESS);
										this.$parent.getAllUsers();
									}
								})
								.catch((error) => {
									this.userLoading = false;
								});
						} else {
							this.userLoading = false;
						}
					} else if (pwdRuleCheck(this.Form.password)) {
						//给密码md5加密处理
						for (let i in this.Form) {
							if (i == "password") {
								this.copyPassword = this.Form[i];
								this.Form[i] = pwdEncrypt(this.Form[i]);
							}
						}
						System.saveUsers(JSON.stringify(this.Form))
							.then((res) => {
								this.userLoading = false;
								if (res.status) {
									this.$message.success(this.LANG.ADD_SUCCESS);
									this.close();
									this.$parent.getAllUsers();
								} else {
									this.Form.password = this.copyPassword;
								}
							})
							.catch((error) => {
								this.userLoading = false;
							});
					} else {
						this.$message.error(this.LANG.PASSWORD_VALID_TIP);
						this.userLoading = false;
					}
				}
			});
		},
	},
};
</script>
<style scoped>
</style>